package com.sunxd.disruptor.test;

/**
 * ProducerType.MULTI  ProducerType.SINGLE 指定单/多线程模式
 * @author: 作者名称
 * @date: 2021-09-27 09:51
 **/

import com.lmax.disruptor.BlockingWaitStrategy;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;
import com.lmax.disruptor.util.DaemonThreadFactory;
import com.sunxd.disruptor.event.LongEvent;
import com.sunxd.disruptor.factory.LongEventFactory;
import com.sunxd.disruptor.handler.LongEventHandler;

import java.util.concurrent.*;

public class Run4_ProducerType {
    public static void main(String[] args) throws InterruptedException {
        Disruptor<LongEvent> disruptor = new Disruptor<LongEvent>(new LongEventFactory(),8, DaemonThreadFactory.INSTANCE, ProducerType.SINGLE,new BlockingWaitStrategy());
        disruptor.handleEventsWith(new LongEventHandler());
        disruptor.start();
        RingBuffer<LongEvent> ringBuffer = disruptor.getRingBuffer();
//        ringBuffer.publishEvent(((longEvent, l) -> longEvent.setValue(10)));
//        ringBuffer.publishEvent((longEvent, sequence, aLong) -> longEvent.setValue(aLong),2L);
//        ringBuffer.publishEvent((longEvent, sequence, aLong,along2) -> longEvent.setValue(aLong+along2),2L,3L);

        int count = 50;
        CyclicBarrier cyclicBarrier = new CyclicBarrier(count);
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i =0 ;i<count;i++){
            int finalI = i;
            executorService.submit(() ->{
                System.out.printf("Thread %s ready to start !" , finalI);
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException e) {

                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }

                for (int j = 0; j < 100; j++) {
                    ringBuffer.publishEvent((longEvent, l) -> {
                        longEvent.setValue(l);
                        System.out.println("生产了：" + count);
                    });
                }


            });
        }
        executorService.shutdown();
        TimeUnit.SECONDS.sleep(3);
        System.out.println(LongEventHandler.count);

    }
}
